package cc.geguol.iodemo.pipleStream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 作者：13687
 * 日期：2017/6/18
 * 项目：IODemo
 * 描述：官道流
 */
public class PileStreamDemo {
	public static void main(String[] args) throws IOException {
		ExecutorService es = Executors.newFixedThreadPool(2);
//		? 这两个管道如何连接呢
		PipedOutputStream out = new PipedOutputStream();
		PipedInputStream in = new PipedInputStream();
		in.connect(out);
		es.execute(new ReadPiple(in));
		es.execute(new WritePiple(out));

		es.shutdown();
	}
}

class ReadPiple implements Runnable{
	public ReadPiple(PipedInputStream pipedInputStream) {
		this.pipedInputStream = pipedInputStream;
	}

	//	需要 关联 管道输入流对象
	private PipedInputStream pipedInputStream;

	@Override
	public void run() {

		byte[] buff=new byte[1024];
		try {
			int i = 0;
			while ((i=pipedInputStream.read(buff))!=-1){
				// 每次打印一个缓存区大小的 内容
				System.out.println("receive:"+new String(buff,0,buff.length));

			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class WritePiple implements Runnable{

	public WritePiple(PipedOutputStream pipedOutputStream) {
		this.pipedOutputStream = pipedOutputStream;
	}

	private PipedOutputStream pipedOutputStream;

	@Override
	public void run() {
		try {
			pipedOutputStream.write("wo ai da ya ".getBytes());
			pipedOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}